//
//  DSAudioView.m
//  DSJY
//
//  Created by 冯华强 on 16/10/21.
//  Copyright © 2016年 dsjy. All rights reserved.
//  音乐的View

#import "DSAudioView.h"
#import "Masonry.h"
#import "DSUnitListeningContent.h"

@interface DSAudioView ()
//背景图View
@property (nonatomic, weak) UIImageView *bgView;
//播放音乐按钮
@property (nonatomic, weak, readwrite) UIButton *audioBtn;
//播放器
@property (nonatomic, strong) AVAudioPlayer *player;
@end

@implementation DSAudioView

#pragma mark - 系统回调
//初始化
+ (__kindof DSAudioView *)audioView
{
    return [[self alloc] init];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        //设置UI
        [self setupView];
    }
    return self;
}

#pragma mark - 设置UI
- (void)setupView
{
    //背景
    UIImageView *bgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"audio"]];
    bgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *gestTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bgViewClick)];
    [bgView addGestureRecognizer:gestTap];
    [self addSubview:bgView];
    self.bgView = bgView;
    
    UIButton *audioBtn = [[UIButton alloc] init];
    [audioBtn setImage:[UIImage imageNamed:@"sy"] forState:UIControlStateNormal];
//    [audioBtn setImage:[UIImage imageNamed:@"a3"] forState:UIControlStateSelected];
    audioBtn.userInteractionEnabled = NO;
    [self addSubview:audioBtn];
    self.audioBtn = audioBtn;
    
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    [audioBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(30, 30));
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(0);
    }];
}

- (void)setListeningContent:(DSUnitListeningContent *)listeningContent
{
    _listeningContent = listeningContent;
    
    //停止－播放音频
    [self stopToPlayMusic];
}

#pragma mark - 设置事件
- (void)bgViewClick
{
    if ([self.delegate respondsToSelector:@selector(audioViewDidBgViewClick:)]) {
        [self.delegate audioViewDidBgViewClick:self];
    }
}

- (void)stopToPlayMusic
{
    [self stopMusic];
    [self playMusic];
}

- (void)playMusic
{
    self.audioBtn.selected = YES;
    self.player = [XCYAudioTool playingMusicWithFileName:self.listeningContent.filePath isBundle:NO];
    //播放本地音乐
    [self.player play];
    self.player.delegate = self.delegate;
}

- (void)stopMusic
{
    self.audioBtn.selected = NO;
    self.player.delegate = nil;
    [XCYAudioTool stopMusicWithFileName:self.listeningContent.filePath];
}

@end
